package com.vinfai.thread.tradition;
/**
 * 传统线程实现生产者、消费者模式
 * 生产者和消费者在同一时间段内共用同一个存储空间
 * @author vinfai
 */
public class ProducerConsumer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Storage storage  = new Storage(100);
		Thread producer1 = new Thread(new Producer(storage),"producer1");
		//Thread producer2 = new Thread(new Producer(storage),"producer2");
		Thread consumer1 = new Thread(new Consumer(storage),"consumer1");
		Thread consumer2 = new Thread(new Consumer(storage),"consumer2");
		Thread consumer3 = new Thread(new Consumer(storage),"consumer3");
		Thread consumer4 = new Thread(new Consumer(storage),"consumer4");
		Thread consumer5 = new Thread(new Consumer(storage),"consumer5");
		producer1.start();
		consumer1.start();
		consumer2.start();
		consumer3.start();
		consumer4.start();
		consumer5.start();
	}
	
	
}

/**
 * 仓库
 */
class Storage {
	private Product[] products = null;
	private int top = 0;
	public Storage(int size){
		products = new Product[size];
	}
	//生产操作
	public synchronized void push(Product product){
		while(top>=products.length){
			try {
				System.out.println("producer is wait.");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		products[top++] = product;
		System.out.println(Thread.currentThread().getName()+" 生成了 "+product+" top is "+top);
		this.notifyAll();//通知等待的消费线程
	}
	//消费操作
	public synchronized Product pop(){
		while(top==0){
			try {
				System.out.println(Thread.currentThread().getName()+ "consumer is wait.");
				this.wait();//仓库已经空，等待生成
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		Product product = products[--top];
		products[top] = null;
		System.out.println(Thread.currentThread().getName()+" 消费了 "+product+" top is "+top);
		this.notifyAll();
		return product;
	}
}
/**
 * 产品
 */
class Product{
	private String id;
	private String name;
	
	public Product(){
		
	}
	public Product(String id,String name){
		this.name = name;
		this.id = id;
	}
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String toString(){
		return "THE PRODUCT IS "+this.id+" ; name :"+this.name;
	}
}

//生产者
class Producer implements Runnable{
	//有个仓库
	private Storage storage; 
	
	public Producer(Storage storage){
		this.storage = storage;
	}
	
	public void run() {
		while(true){
			Product product = new Product("000000001","苹果");
			storage.push(product);
		}
	}
}

//消费者
class Consumer implements Runnable{
	private Storage storage;
	public Consumer(Storage storage){
		this.storage = storage;
	}
	public void run(){ 
		while(true){
			Product product = storage.pop();
		}
	}
}


